package com.hh.service.service.impl.message.consumer;

import cn.hutool.core.util.ObjectUtil;
import com.hh.common.config.RabbitMqConfig;
import com.hh.common.model.order.StoreOrder;
import com.hh.service.service.NewOrderService;
import com.hh.service.service.OrderPayService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class OrderConsumerMessage {

    @Autowired
    private NewOrderService newOrderService;

    @Autowired
    private OrderPayService orderPayService;

    /**
     * 订单超时未支付消息消费
     * @param message
     * @param orderNo
     * @param channel
     */
    @RabbitListener(queues = {RabbitMqConfig.ORDER_DELAYED_CANCEL_QUEUE})
    public void autoCancelOrder(Message message, String orderNo, Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        StoreOrder order = newOrderService.getByOderId(orderNo);

        try {
            if(ObjectUtil.isNull(order)){
                channel.basicAck(deliveryTag, false);
            }else {
                Boolean b = this.newOrderService.doCancel(order,"到期未支付系统自动取消");
                if (b) {
                    channel.basicAck(deliveryTag, false);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RabbitListener(queues = {RabbitMqConfig.ORDER_PAY_SUCCESS_AFTER_QUEUE})
    public void orderPaySuccess(Message message, String orderNo, Channel channel){
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        StoreOrder order = newOrderService.getByOderId(orderNo);

        try {
            if(ObjectUtil.isNull(order)){
                channel.basicAck(deliveryTag, false);
            }else {
                boolean result = orderPayService.paySuccess(order);
                if(result){
                    channel.basicAck(deliveryTag, false);
                }
            }

        }catch (IOException e){
            e.printStackTrace();
        }

    }
}
